function StringFormat() 
{
  var res = arguments[0];
  for (var i = 1; i < arguments.length; i++)
    res = res + " ... " + arguments[i];
  return res;
};

var window = this;

//-------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft Corporation. All rights reserved.
// [ATLAS]
//-------------------------------------------------------------------------------------------------

Function.createCallback = function Function$createCallback(method, context) {
    return function() {
        var l = arguments.length;
        if (l > 0) {
                        var args = [];
            for (var i = 0; i < l; i++) {
                args[i] = arguments[i];
            };
            args[l] = context;
            return method.apply(this, args);
        };
        return method.call(this, context);
    };
};

Function.createDelegate = function Function$createDelegate(instance, method) {
    return function() {
        return method.apply(instance, arguments);
    };
};

Function.emptyFunction = Function.emptyMethod = function Function$emptyMethod() {
    if (arguments.length !== 0) throw Error.parameterCount();
};


//-------------------------------------------------------------------------------------------------

Error.__typeName = 'Error';
Error.__class = true;
Error.create = function Error$create(message, errorInfo) {
    var e = new Error(message);
    e.message = message;

    if (errorInfo) {
        for (var v in errorInfo) {
            e[v] = errorInfo[v];
        };
    };

    e.popStackFrame();
    return e;
};

Error.argument = function Error$argument(paramName, message) {
    var displayMessage = "Sys.ArgumentException: " + (message ? message : Sys.Res.argument);
    if (paramName) {
        displayMessage += "\n" + StringFormat(Sys.Res.paramName, paramName);
    };

    var e = Error.create(displayMessage, { name: "Sys.ArgumentException", paramName: paramName });
    e.popStackFrame();
    return e;
};

Error.argumentNull = function Error$argumentNull(paramName, message) {
    var displayMessage = "Sys.ArgumentNullException: " + (message ? message : Sys.Res.argumentNull);
    if (paramName) {
        displayMessage += "\n" + StringFormat(Sys.Res.paramName, paramName);
    };

    var e = Error.create(displayMessage, { name: "Sys.ArgumentNullException", paramName: paramName });
    e.popStackFrame();
    return e;
};

Error.argumentOutOfRange = function Error$argumentOutOfRange(paramName, actualValue, message) {
    var displayMessage = "Sys.ArgumentOutOfRangeException: " + (message ? message : Sys.Res.argumentOutOfRange);
    if (paramName) {
        displayMessage += "\n" + StringFormat(Sys.Res.paramName, paramName);
    };

                if (typeof(actualValue) !== "undefined" && actualValue !== null) {
        displayMessage += "\n" + StringFormat(Sys.Res.actualValue, actualValue);
    };

    var e = Error.create(displayMessage, {
        name: "Sys.ArgumentOutOfRangeException",
        paramName: paramName,
        actualValue: actualValue
    });
    e.popStackFrame();
    return e;
};

Error.argumentType = function Error$argumentType(paramName, actualType, expectedType, message) {
    var displayMessage = "Sys.ArgumentTypeException: ";
    if (message) {
        displayMessage += message;
    };
    else if (actualType && expectedType) {
        displayMessage +=
            StringFormat(Sys.Res.argumentTypeWithTypes, actualType.getName(), expectedType.getName());
    };
    else {
        displayMessage += Sys.Res.argumentType;
    };

    if (paramName) {
        displayMessage += "\n" + StringFormat(Sys.Res.paramName, paramName);
    };

    var e = Error.create(displayMessage, {
        name: "Sys.ArgumentTypeException",
        paramName: paramName,
        actualType: actualType,
        expectedType: expectedType
    });
    e.popStackFrame();
    return e;
};

Error.argumentUndefined = function Error$argumentUndefined(paramName, message) {
    var displayMessage = "Sys.ArgumentUndefinedException: " + (message ? message : Sys.Res.argumentUndefined);
    if (paramName) {
        displayMessage += "\n" + StringFormat(Sys.Res.paramName, paramName);
    };

    var e = Error.create(displayMessage, { name: "Sys.ArgumentUndefinedException", paramName: paramName });
    e.popStackFrame();
    return e;
};

Error.format = function Error$format(message) {
    var displayMessage = "Sys.FormatException: " + (message ? message : Sys.Res.format);
    var e = Error.create(displayMessage, {name: 'Sys.FormatException'});
    e.popStackFrame();
    return e;
};

Error.invalidOperation = function Error$invalidOperation(message) {
    var displayMessage = "Sys.InvalidOperationException: " + (message ? message : Sys.Res.invalidOperation);

    var e = Error.create(displayMessage, {name: 'Sys.InvalidOperationException'});
    e.popStackFrame();
    return e;
};

Error.notImplemented = function Error$notImplemented(message) {
    var displayMessage = "Sys.NotImplementedException: " + (message ? message : Sys.Res.notImplemented);

    var e = Error.create(displayMessage, {name: 'Sys.NotImplementedException'});
    e.popStackFrame();
    return e;
};

Error.parameterCount = function Error$parameterCount(message) {
    var displayMessage = "Sys.ParameterCountException: " + (message ? message : Sys.Res.parameterCount);
    var e = Error.create(displayMessage, {name: 'Sys.ParameterCountException'});
    e.popStackFrame();
    return e;
};

Error.prototype.popStackFrame = function Error$popStackFrame() {
    if (arguments.length !== 0) throw Error.parameterCount();

                            
    if (typeof(this.stack) === "undefined" || this.stack === null ||
        typeof(this.fileName) === "undefined" || this.fileName === null ||
        typeof(this.lineNumber) === "undefined" || this.lineNumber === null) {
        return;
    };

    var stackFrames = this.stack.split("\n");

                var currentFrame = stackFrames[0];
    var pattern = this.fileName + ":" + this.lineNumber;
    while(typeof(currentFrame) !== "undefined" &&
          currentFrame !== null &&
          currentFrame.indexOf(pattern) === -1) {
        stackFrames.shift();
        currentFrame = stackFrames[0];
    };

    var nextFrame = stackFrames[1];

        if (typeof(nextFrame) === "undefined" || nextFrame === null) {
        return;
    };

        var nextFrameParts = nextFrame.match(/@(.*):(\d+)$/);
    if (typeof(nextFrameParts) === "undefined" || nextFrameParts === null) {
        return;
    };

    this.fileName = nextFrameParts[1];

        this.lineNumber = parseInt(nextFrameParts[2]);

    stackFrames.shift();
    this.stack = stackFrames.join("\n");
};

//-------------------------------------------------------------------------------------------------

Array.indexOf = function (array, item, start) {
    if (typeof(item) === "undefined") return -1;
    var length = array.length;
    if (length !== 0) {
        start = start - 0;
        if (isNaN(start)) { start = 0; };
        else 
        {
            if (isFinite(start)) { start = start - (start % 1); };
            if (start < 0) { start = Math.max(0, length + start); };
        };
        for (var i = start; i < length; i++) {
            if ((typeof(array[i]) !== "undefined") && (array[i] === item)) {
                return i;
            };
        };
    };
    return -1;
};

//-------------------------------------------------------------------------------------------------
if (!window) this.window = this;
window.Type = Function;
window.__rootNamespaces = [];
window.__registeredTypes = {};

Type.__fullyQualifiedIdentifierRegExp = new RegExp("^[^.0-9 \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\]([^ \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\]*[^. \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\])?$", "i");
Type.__identifierRegExp = new RegExp("^[^.0-9 \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\][^. \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\]*$", "i");

Type.prototype.callBaseMethod = function Type$callBaseMethod(instance, name, baseArguments) {
    var baseMethod = this.getBaseMethod(instance, name);
    if (!baseMethod) throw Error.invalidOperation(StringFormat(Sys.Res.methodNotFound, name));
    if (!baseArguments) {
        return baseMethod.apply(instance);
    };
    else {
        return baseMethod.apply(instance, baseArguments);
    };
};

Type.prototype.getBaseMethod = function Type$getBaseMethod(instance, name) {
    if (!this.isInstanceOfType(instance)) throw Error.argumentType('instance', Object.getType(instance), this);
    var baseType = this.getBaseType();
    if (baseType) {
        var baseMethod = baseType.prototype[name];
        return (baseMethod instanceof Function) ? baseMethod : null;
    };

    return null;
};

Type.prototype.getBaseType = function Type$getBaseType() {
    if (arguments.length !== 0) throw Error.parameterCount();
    return (typeof(this.__baseType) === "undefined") ? null : this.__baseType;
};

Type.prototype.getInterfaces = function Type$getInterfaces() {
    if (arguments.length !== 0) throw Error.parameterCount();
    var result = [];
    var type = this;
    while(type) {
        var interfaces = type.__interfaces;
        if (interfaces) {
            for (var i = 0, l = interfaces.length; i < l; i++) {
                var interfaceType = interfaces[i];
                if (!Array.contains(result, interfaceType)) {
                    result[result.length] = interfaceType;
                };
            };
        };
        type = type.__baseType;
    };
    return result;
};

Type.prototype.getName = function Type$getName() {
    if (arguments.length !== 0) throw Error.parameterCount();
    return (typeof(this.__typeName) === "undefined") ? "" : this.__typeName;
};

Type.prototype.implementsInterface = function Type$implementsInterface(interfaceType) {
    this.resolveInheritance();

    var interfaceName = interfaceType.getName();
    var cache = this.__interfaceCache;
    if (cache) {
        var cacheEntry = cache[interfaceName];
        if (typeof(cacheEntry) !== 'undefined') return cacheEntry;
    };
    else {
        cache = this.__interfaceCache = {};
    };

    var baseType = this;
    while (baseType) {
        var interfaces = baseType.__interfaces;
        if (interfaces) {
            if (Array.indexOf(interfaces, interfaceType) !== -1) {
                return cache[interfaceName] = true;
            };
        };

        baseType = baseType.__baseType;
    };

    return cache[interfaceName] = false;
};

Type.prototype.inheritsFrom = function Type$inheritsFrom(parentType) {
    this.resolveInheritance();
    var baseType = this.__baseType;
    while (baseType) {
        if (baseType === parentType) {
            return true;
        };
        baseType = baseType.__baseType;
    };

    return false;
};

Type.prototype.initializeBase = function Type$initializeBase(instance, baseArguments) {
    if (!this.isInstanceOfType(instance)) throw Error.argumentType('instance', Object.getType(instance), this);

    this.resolveInheritance();
    if (this.__baseType) {
        if (!baseArguments) {
            this.__baseType.apply(instance);
        };
        else {
            this.__baseType.apply(instance, baseArguments);
        };
    };

    return instance;
};

Type.prototype.isImplementedBy = function Type$isImplementedBy(instance) {
    if (typeof(instance) === "undefined" || instance === null) return false;

    var instanceType = Object.getType(instance);
    return !!(instanceType.implementsInterface && instanceType.implementsInterface(this));
};

Type.prototype.isInstanceOfType = function Type$isInstanceOfType(instance) {
    if (typeof(instance) === "undefined" || instance === null) return false;

    if (instance instanceof this) return true;

    var instanceType = Object.getType(instance);
    return !!(instanceType === this) ||
           (instanceType.inheritsFrom && instanceType.inheritsFrom(this)) ||
           (instanceType.implementsInterface && instanceType.implementsInterface(this));
};

Type.prototype.registerClass = function Type$registerClass(typeName, baseType, interfaceTypes) {
    if (!Type.__fullyQualifiedIdentifierRegExp.test(typeName)) throw Error.argument('typeName', Sys.Res.notATypeName);
        var parsedName;
    try {
        parsedName = eval(typeName);
    };
    catch(e) {
        throw Error.argument('typeName', Sys.Res.argumentTypeName);
    };
    if (parsedName !== this) throw Error.argument('typeName', Sys.Res.badTypeName);
        if (window.__registeredTypes[typeName]) throw Error.invalidOperation(StringFormat(Sys.Res.typeRegisteredTwice, typeName));

            if ((arguments.length > 1) && (typeof(baseType) === 'undefined')) throw Error.argumentUndefined('baseType');
    if (baseType && !baseType.__class) throw Error.argument('baseType', Sys.Res.baseNotAClass);

    this.prototype.constructor = this;
    this.__typeName = typeName;
    this.__class = true;
    if (baseType) {
        this.__baseType = baseType;
        this.__basePrototypePending = true;
    };
        if (!window.__classes) window.__classes = {};
    window.__classes[typeName.toUpperCase()] = this;

                if (interfaceTypes) {
        this.__interfaces = [];
        for (var i = 2; i < arguments.length; i++) {
            var interfaceType = arguments[i];
            if (!interfaceType.__interface) throw Error.argument('interfaceTypes[' + (i - 2) + ']', Sys.Res.notAnInterface);
            this.resolveInheritance();
            for (var methodName in interfaceType.prototype) {
                var method = interfaceType.prototype[methodName];
                if (!this.prototype[methodName]) {
                    this.prototype[methodName] = method;
                };
            };
            this.__interfaces.push(interfaceType);
        };
    };
    window.__registeredTypes[typeName] = true;

    return this;
};

Type.prototype.registerInterface = function Type$registerInterface(typeName) {
    if (!Type.__fullyQualifiedIdentifierRegExp.test(typeName)) throw Error.argument('typeName', Sys.Res.notATypeName);
        var parsedName;
    try {
        parsedName = eval(typeName);
    };
    catch(e) {
        throw Error.argument('typeName', Sys.Res.argumentTypeName);
    };
    if (parsedName !== this) throw Error.argument('typeName', Sys.Res.badTypeName);
        if (window.__registeredTypes[typeName]) throw Error.invalidOperation(StringFormat(Sys.Res.typeRegisteredTwice, typeName));
    this.prototype.constructor = this;
    this.__typeName = typeName;
    this.__interface = true;
    window.__registeredTypes[typeName] = true;

    return this;
};

Type.prototype.resolveInheritance = function Type$resolveInheritance() {
    if (arguments.length !== 0) throw Error.parameterCount();

    if (this.__basePrototypePending) {
        var baseType = this.__baseType;

        baseType.resolveInheritance();

        for (var memberName in baseType.prototype) {
            var memberValue = baseType.prototype[memberName];
            if (!this.prototype[memberName]) {
                this.prototype[memberName] = memberValue;
            };
        };
        delete this.__basePrototypePending;
    };
};

Type.getRootNamespaces = function Type$getRootNamespaces() {
    if (arguments.length !== 0) throw Error.parameterCount();
    return Array.clone(window.__rootNamespaces);
};

Type.isClass = function Type$isClass(type) {
    if ((typeof(type) === 'undefined') || (type === null)) return false;
    return !!type.__class;
};

Type.isInterface = function Type$isInterface(type) {
    if ((typeof(type) === 'undefined') || (type === null)) return false;
    return !!type.__interface;
};

Type.isNamespace = function Type$isNamespace(object) {
    if ((typeof(object) === 'undefined') || (object === null)) return false;
    return !!object.__namespace;
};

Type.parse = function Type$parse(typeName, ns) {
    var fn;
    if (ns) {
        if (!window.__classes) return null;
        fn = window.__classes[ns.getName().toUpperCase() + '.' + typeName.toUpperCase()];
        return fn || null;
    };
    if (!typeName) return null;
    if (!Type.__htClasses) {
        Type.__htClasses = {};
    };
    fn = Type.__htClasses[typeName];
    if (!fn) {
        fn = eval(typeName);
        if (typeof(fn) !== 'function') throw Error.argument('typeName', Sys.Res.notATypeName);
        Type.__htClasses[typeName] = fn;
    };
    return fn;
};

Type.registerNamespace = function Type$registerNamespace(namespacePath) {
    if (!Type.__fullyQualifiedIdentifierRegExp.test(namespacePath)) throw Error.argument('namespacePath', Sys.Res.invalidNameSpace);
    var rootObject = window;
    var namespaceParts = namespacePath.split('.');

    for (var i = 0; i < namespaceParts.length; i++) {
        var currentPart = namespaceParts[i];
        var ns = rootObject[currentPart];
        if (ns && !ns.__namespace) {
            throw Error.invalidOperation(StringFormat(Sys.Res.namespaceContainsObject, namespaceParts.splice(0, i + 1).join('.')));
        };
        if (!ns) {
            ns = rootObject[currentPart] = {};
            if (i === 0) {
                window.__rootNamespaces[window.__rootNamespaces.length] = ns;
            };
            ns.__namespace = true;
            ns.__typeName = namespaceParts.slice(0, i + 1).join('.');
            var parsedName;
            try {
                parsedName = eval(ns.__typeName);
            };
            catch(e) {
                parsedName = null;
            };
            if (parsedName !== ns) {
                delete rootObject[currentPart];
                throw Error.argument('namespacePath', Sys.Res.invalidNameSpace);
            };
            ns.getName = function ns$getName() {return this.__typeName;};
        };
        rootObject = ns;
    };
};

//-------------------------------------------------------------------------------------------------
Object.__typeName = 'Object';
Object.__class = true;
Object.getType = function Object$getType(instance) {
    var ctor = instance.constructor;
    if (!ctor || (typeof(ctor) !== "function") || !ctor.__typeName || (ctor.__typeName === 'Object')) {
        return Object;
    };
    return ctor;
};

Object.getTypeName = function Object$getTypeName(instance) {
    return Object.getType(instance).getName();
};

//-------------------------------------------------------------------------------------------------

Type.prototype.registerEnum = function Type$registerEnum(name, flags) {
    if (!Type.__fullyQualifiedIdentifierRegExp.test(name)) throw Error.argument('name', Sys.Res.notATypeName);
        var parsedName;
    try {
        parsedName = eval(name);
    };
    catch(e) {
        throw Error.argument('name', Sys.Res.argumentTypeName);
    };
    if (parsedName !== this) throw Error.argument('name', Sys.Res.badTypeName);
    if (window.__registeredTypes[name]) throw Error.invalidOperation(StringFormat(Sys.Res.typeRegisteredTwice, name));
    for (var i in this.prototype) {
        var val = this.prototype[i];
        if (!Type.__identifierRegExp.test(i)) throw Error.invalidOperation(StringFormat(Sys.Res.enumInvalidValueName, i));
        if (typeof(val) !== 'number' || (val % 1) !== 0) throw Error.invalidOperation(Sys.Res.enumValueNotInteger);
        if (typeof(this[i]) !== 'undefined') throw Error.invalidOperation(StringFormat(Sys.Res.enumReservedName, i));
    };
    for (var i in this.prototype) {
        this[i] = this.prototype[i];
    };
    this.__typeName = name;
    this.parse = Sys$Enum$parse;
    this.__string = this.toString();
    this.toString = Sys$Enum$toString;
    this.__flags = flags;
    this.__enum = true;
    window.__registeredTypes[name] = true;
};

Type.isEnum = function Type$isEnum(type) {
    if ((typeof(type) === 'undefined') || (type === null)) return false;
    return !!type.__enum;
};

Type.isFlags = function Type$isFlags(type) {
    if ((typeof(type) === 'undefined') || (type === null)) return false;
    return !!type.__flags;
};

//-------------------------------------------------------------------------------------------------
// [/ATLAS]
//-------------------------------------------------------------------------------------------------

Type.registerNamespace("Sys");
Sys.Res={
  'argumentTypeName':'Value is not the name of an existing type.',
  'methodRegisteredTwice':'Method {0} has already been registered.',
  'cantSetIdAfterInit':'The id property can\'t be set on this object after initialization.',
  'componentCantSetIdAfterAddedToApp':'The id property of a component can\'t be set after it\'s been added to the Application object.',
  'behaviorDuplicateName':'A behavior with name \'{0}\' already exists or it is the name of an existing property on the target element.',
  'notATypeName':'Value is not a valid type name.',
  'typeShouldBeTypeOrString':'Value is not a valid type or a valid type name.',
  'boolTrueOrFalse':'Value must be \'true\' or \'false\'.',
  'stringFormatInvalid':'The format string is invalid.',
  'referenceNotFound':'Component \'{0}\' was not found.',
  'enumReservedName':'\'{0}\' is a reserved name that can\'t be used as an enum value name.',
  'eventHandlerNotFound':'Handler not found.',
  'circularParentChain':'The chain of control parents can\'t have circular references.',
  'undefinedEvent':'\'{0}\' is not an event.',
  'notAMethod':'{0} is not a method.',
  'propertyUndefined':'\'{0}\' is not a property or an existing field.',
  'eventHandlerInvalid':'Handler was not added through the Sys.UI.DomEvent.addHandler method.',
  'scriptLoadFailedDebug':'The script \'{0}\' failed to load. Check for:\r\n Inaccessible path.\r\n Script errors. (IE) Enable \'Display a notification about every script error\' under advanced settings.\r\n Missing call to Sys.Application.notifyScriptLoaded().',
  'propertyNotWritable':'\'{0}\' is not a writable property.',
  'enumInvalidValueName':'\'{0}\' is not a valid name for an enum value.',
  'controlAlreadyDefined':'A control is already associated with the element.',
  'namespaceContainsObject':'Object {0} already exists and is not a namespace.',
  'cantAddNonFunctionhandler':'Can\'t add a handler that is not a function.',
  'scriptLoaderAlreadyLoading':'ScriptLoader.loadScripts cannot be called while the ScriptLoader is already loading scripts.',
  'invalidNameSpace':'Value is not a valid namespace identifier.',
  'notAnInterface':'Value is not a valid interface.',
  'eventHandlerNotFunction':'Handler must be a function.',
  'propertyNotAnArray':'\'{0}\' is not an Array property.',
  'typeRegisteredTwice':'Type {0} has already been registered.',
  'cantSetNameAfterInit':'The name property can\'t be set on this object after initialization.',
  'appDuplicateComponent':'Two components with the same id \'{0}\' can\'t be added to the application.',
  'appComponentMustBeInitialized':'Components must be initialized before they are added to the Application object.',
  'baseNotAClass':'Value is not a class.',
  'methodNotFound':'No method found with name \'{0}\'.',
  'arrayParseBadFormat':'Value must be a valid string representation for an array. It must start with a \'[\' and end with a \']\'.',
  'cantSetId':'The id property can\'t be set on this object.',
  'stringFormatBraceMismatch':'The format string contains an unmatched opening or closing brace.',
  'enumValueNotInteger':'An enumeration definition can only contain integer values.',
  'propertyNullOrUndefined':'Cannot set the properties of \'{0}\' because it returned a null value.',
  'componentCantSetIdTwice':'The id property of a component can\'t be set more than once.',
  'createComponentOnDom':'Value must be null for Components that are not Controls or Behaviors.',
  'createNotComponent':'{0} does not derive from Sys.Component.',
  'createNoDom':'Value must not be null for Controls and Behaviors.',
  'cantAddWithoutId':'Can\'t add a component that doesn\'t have an id.',
  'badTypeName':'Value is not the name of the type being registered or the name is a reserved word.',
  'argumentInteger':'Value must be an integer.',
  'scriptLoadMultipleCallbacks':'The script \'{0}\' contains multiple calls to Sys.Application.notifyScriptLoaded(). Only one is allowed.',
  'invokeCalledTwice':'Cannot call invoke more than once.',
  'webServiceFailed':'The server method \'{0}\' failed with the following error: {1}',
  'argumentType':'Object cannot be converted to the required type.',
  'argumentNull':'Value cannot be null.',
  'controlCantSetId':'The id property can\'t be set on a control.',
  'formatBadFormatSpecifier':'Format specifier was invalid.',
  'webServiceFailedNoMsg':'The server method \'{0}\' failed.',
  'argumentDomElement':'Value must be a DOM element.',
  'invalidExecutorType':'Could not create a valid Sys.Net.WebRequestExecutor from: {0}.',
  'cannotCallBeforeResponse':'Cannot call {0} when responseAvailable is false.',
  'actualValue':'Actual value was {0}.',
  'enumInvalidValue':'\'{0}\' is not a valid value for enum {1}.',
  'scriptLoadFailed':'The script \'{0}\' could not be loaded.',
  'parameterCount':'Parameter count mismatch.',
  'cannotDeserializeEmptyString':'Cannot deserialize empty string.',
  'formatInvalidString':'Input string was not in a correct format.',
  'invalidTimeout':'Value must be greater than or equal to zero.',
  'cannotAbortBeforeStart':'Cannot abort when executor has not started.',
  'argument':'Value does not fall within the expected range.',
  'cannotDeserializeInvalidJson':'Cannot deserialize. The data does not correspond to valid JSON.',
  'invalidHttpVerb':'httpVerb cannot be set to an empty or null string.',
  'nullWebRequest':'Cannot call executeRequest with a null webRequest.',
  'eventHandlerInvalid':'Handler was not added through the Sys.UI.DomEvent.addHandler method.',
  'cannotSerializeNonFiniteNumbers':'Cannot serialize non finite numbers.',
  'argumentUndefined':'Value cannot be undefined.',
  'webServiceInvalidReturnType':'The server method \'{0}\' returned an invalid type. Expected type: {1}',
  'servicePathNotSet':'The path to the web service has not been set.',
  'argumentTypeWithTypes':'Object of type \'{0}\' cannot be converted to type \'{1}\'.',
  'cannotCallOnceStarted':'Cannot call {0} once started.',
  'badBaseUrl1':'Base URL does not contain ://.',
  'badBaseUrl2':'Base URL does not contain another /.',
  'badBaseUrl3':'Cannot find last / in base URL.',
  'setExecutorAfterActive':'Cannot set executor after it has become active.',
  'paramName':'Parameter name: {0}',
  'cannotCallOutsideHandler':'Cannot call {0} outside of a completed event handler.',
  'format':'One of the identified items was in an invalid format.',
  'assertFailedCaller':'Assertion Failed: {0}\r\nat {1}',
  'argumentOutOfRange':'Specified argument was out of the range of valid values.',
  'webServiceTimedOut':'The server method \'{0}\' timed out.',
  'notImplemented':'The method or operation is not implemented.',
  'assertFailed':'Assertion Failed: {0}',
  'invalidOperation':'Operation is not valid due to the current state of the object.',
  'breakIntoDebugger':'{0}\r\n\r\nBreak into debugger?'
};

//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
// ************************************************************************************************
// serialization..
function $get(el) { 
    return document.getElementById(el);
}
// ************************************************************************************************

var createGenericHandler = function (handler) { 
  return function(e) {
    if (!e) { if (window.event) e=window.event; }
    var ce = CreateObject(new CancelEventArgs(), [false]); // TODO: namespace
    handler.invoke(this, ce);
    if (e) e.returnValue = !ce.get_Canceled();
    return !ce.get_Canceled();
  };
}

var createMouseHandler = function (handler) { 
  return function(e) {
    if (!e) e=event;
    var pos = new Position(); // TODO: namespace
  	if (e.pageX || e.pageY) {
  		pos.set_Left(e.pageX);
      pos.set_Top(e.pageY);
    } else if (e.clientX || e.clientY) 	{
  		pos.set_Left(e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft);
      pos.set_Top(e.clientY + document.body.scrollTop + document.documentElement.scrollTop);
  	}
  	var ce = new MouseEventArgs(); ce.ctor(e.button, pos); // TODO: namespace
    handler.invoke(this, ce);
    if (e) e.returnValue = !ce.get_Canceled();
    return !ce.get_Canceled();
  };
}


function createEvent() {
  return new function() {
    this.handlers = new Array();
    this.add = function(o) { this.handlers.push(o); }
    this.remove = function(o) { var i = this.handlers.indexOf(o); if (i != -1) this.handlers.removeAt(i); }
    this.invoke = function(sender,e) { 
    for (var i = 0; i<this.handlers.length; i++) { 
    this.handlers[i](sender,e); } }
  }
}

function attachHandler(el, name, func)
{
    if (el.addEventListener)
        el.addEventListener(name, func, true)
    else
        el.attachEvent("on" + name, func);        
}

// ************************************************************************************************

Type.registerNamespace("Lib");

Lib.Utils = new Object();
Lib.Convert = new Object();

// JS primitive language constructs & ugly dynamic tricks
Lib.Utils.TryCatch = function(f,h) { try { return f(); } catch(e) { return h(); } }
Lib.Utils.Not = function(o) { return !o; }
Lib.Utils.Cast = function(o) { return o; }
Lib.Utils.Subtract = function(a,b) { return a-b; }
Lib.Utils.FailWith = function(o) { /*alert("DEBUG: throwing exception: "+o); */ throw o; }
Lib.Utils.Ignore = function(o) { }
Lib.Utils.GetMember = function(o, m) { return eval("o." + m); }
Lib.Utils.SetMember = function(o, m, v) { eval("o." + m + " = v;"); }
Lib.Utils.InvokeMember = function(o, m, args) { return eval("o." + m + ".apply(o, args)"); }
Lib.Utils.InvokeStatic = function(m, args) { return eval(m + ".apply(null, args)"); }
Lib.Utils.HasValue = function(o) { if (o!=null) return true; else return false; }
Lib.Utils.MembersIter = function(o, f) { for(var v in o) { f(v); }; }
Lib.Utils.StrLength = function(s) { return s.length; }
Lib.Utils.ArrayZeroCreate = function(n, ty) { var arr = new Array(); for(var i=0; i<n; i++) arr[i]=null; return CreateArray(arr, ty); }
Lib.Utils.OpIndexedAssign = function(col, i, v) { if (col.set_Item) col.set_Item(i,v); else col[i]=v; }
Lib.Utils.OpIndexedLookup = function(col, i, v) { if (col.get_Item) return col.get_Item(i); else return col[i]; }
Lib.Utils.GetArguments = function(args) { var ret = new Array(); for(var i=0; i<args.length; i++) ret.push(args[i]); return ret; } // it's not a real array for some reason
Lib.Convert.ToString = function(o) { if (o && o.ToString) return o.ToString(); else return ""+o; }
Lib.Convert.ToFloat  = function(o) { return o*1.0; }
Lib.Convert.ToInt    = function(o) { return o*1; }

Array.prototype.get_Item = function(i) { if (i>=this.length) Lib.Utils.FailWith("Index out of range!"); return this[i]; }
Array.prototype.set_Item = function(i, v) { if (i>=this.length) Lib.Utils.FailWith("Index out of range!"); this[i] = v; }
Array.prototype.removeAt = function(i) { this.splice(i,1); }
Array.prototype.indexOf = function(v) { for(var i=0; i<this.length; i++) { if (v == this[i]) return i; } return -1; }

String.prototype.startsWith = function(s) { return this.indexOf(s) == 0; }
String.prototype.toCharArray = function() { return this.split(""); }
String.prototype.replaceAll = function(s,rep) { 
  var res = "";
  var tmp = this; 
  var idx = 0;
  while((idx = tmp.indexOf(s)) != -1)
  {
    res = res + tmp.substr(0, idx) + rep;
    tmp = tmp.substr(idx+s.length);
  }
  return res + tmp; 
}


// ************************************************************************************************

var prevOnLoad = window.onload;
var loaded = false;
var thisPage = null;

window.onload = function(e) { 
  if (prevOnLoad!=null) prevOnLoad(e); 
  loaded = true;
  thisPage.OnClientLoad();
};

function CreateArray(arr, ty) 
{
  arr.__js_special__ = "array";
  arr.__net_type__ = ty;
  return arr;
}

function CreateRecord(rec, ty) 
{
  rec.__js_special__ = "record";
  rec.__net_type__ = ty;
  return rec;
}

function CreatePage(el, args)
{
  el.ctor.apply(el, args);
  initialized = true;
  el.OnClientInit();
  return el;
}

function CreateObject(el, args)
{
  el.ctor.apply(el, args);
  return el;
}

var wraperCache = new Array();

function CreateElement(el, args)
{
  el.ctor.apply(el, args);
  wraperCache[el.id] = el;
  return el;
}

function DropWrapper(id)
{
  wraperCache[id] = null;
}

function getAndWrapOption(ddl,i)
{
  return CreateElement(new Dom.Element(), [ddl.el.item(i)]);
}

function clearAllOptions(ddl)
{
  while(ddl.el.length != 0)
    ddl.el.remove(0);
}

function createAndAddOption(ddl)
{
  var el = document.createElement("OPTION")
  ddl.el.add(el)
  return CreateElement(new Dom.Element(), [el]);
}

function WrapElement(el)
{
  if (!wraperCache[el.id]) 
  { 
    var wel = CreateElement(new Dom.Element(), [el]); 
    wraperCache[el.id] = wel;
    wel.OnClientInit();
    wel.OnClientLoad();
  }
  return (wraperCache[el.id]);
}


// ************************************************************************************************

Type.registerNamespace("Dom");

Dom.Page = function() { 
    this.Controls = null;
    this.mouseDown = null;
    this.mouseUp = null;
    this.mouseMove = null;
}
Dom.Page.prototype = {
    ctor : function() {
        this.Controls = CreateObject(new List(), []);
        this.mouseDown = createEvent();
        this.mouseUp = createEvent();
        this.mouseMove = createEvent();
    },
    OnClientInitControls : function() {
    },
    OnClientInit : function() {
      attachHandler(document.body, 'mousedown', Function.createDelegate(this, createMouseHandler(this.mouseDown) ));
      attachHandler(document.body, 'mouseup', Function.createDelegate(this, createMouseHandler(this.mouseUp) ));
      attachHandler(document.body, 'mousemove', Function.createDelegate(this, createMouseHandler(this.mouseMove) ));
      
      this.OnClientInitControls();
      for(var i=0; i<this.Controls.get_Length(); i++)
        this.Controls.get_Item(i).OnClientInit();
    },
    OnClientLoad : function() { 
      for(var i=0; i<this.Controls.get_Length(); i++)
        this.Controls.get_Item(i).OnClientLoad();
      if (this.Client_Load) this.Client_Load();
    },
    get_size : function() {
      var ret = new Object();
      var test = document.body.scrollHeight > document.body.offsetHeight;
      ret.width = test?document.body.scrollWidth:document.body.offsetWidth;
      ret.height = test?document.body.scrollHeight:document.body.offsetHeight;
      return ret;
    },    
    get_viewRect : function() {
      var rc = new Object();
      rc.left = document.documentElement.scrollLeft;
      rc.top = document.documentElement.scrollTop;
      rc.height = document.documentElement.clientHeight;
      rc.width = document.documentElement.clientWidth;
      return rc;
    },
    get_MouseDown : function() { return this.mouseDown; },
    get_MouseUp : function() { return this.mouseUp; },
    get_MouseMove : function() { return this.mouseMove; }
};
Dom.Page.registerClass('Dom.Page');

// ************************************************************************************************

Dom.Element = function()
{
    Dom.Element.initializeBase(this);
    this.Controls = null;
    this.el = null;
    this.id = null;
    this.mouseDown = null;
    this.mouseUp = null;
    this.mouseMove = null;
    this.selectStart = null;
    this.click = null;
}    
Dom.Element.prototype = {          
    ctor : function(el) {
        this.Controls = CreateObject(new List(), []);
        this.el = el;
        this.id = el.id;
        this.mouseDown = createEvent();
        this.mouseUp = createEvent();
        this.mouseMove = createEvent();
        this.selectStart = createEvent();    
        this.click = createEvent();
    },
    OnClientInitControls : function() {
    },
    OnClientInit : function() {
      attachHandler(this.el, 'mousedown', Function.createDelegate(this, createMouseHandler(this.mouseDown) ));
      attachHandler(this.el, 'mouseup', Function.createDelegate(this, createMouseHandler(this.mouseUp) ));
      attachHandler(this.el, 'mousemove', Function.createDelegate(this, createMouseHandler(this.mouseMove) ));
      attachHandler(this.el, 'selectstart', Function.createDelegate(this, createGenericHandler(this.selectStart) ));
      attachHandler(this.el, 'click', Function.createDelegate(this, createGenericHandler(this.click) ));
      
      this.OnClientInitControls();
      for(var i=0; i<this.Controls.get_Length(); i++)
        this.Controls.get_Item(i).OnClientInit();
    },
    OnClientLoad : function() { 
      this.Client_Load();
    },
    Client_Load : function() {
      // ni
    },
    set_Size : function(size) {
      this.el.style.width = size.width+'px';
      this.el.style.height = size.height+'px';
    },
    set_Position : function(pos) {
      this.el.style.left = pos.left+'px';
      this.el.style.top = pos.top+'px';
    },
    get_Position : function() {
      var pos = new Object();
      var parent = this.el;
      pos.left = this.el.offsetLeft; pos.top = this.el.offsetTop;
      while(parent = parent.offsetParent)
      {
        pos.left += parent.offsetLeft; 
        pos.top += parent.offsetTop;
      }
      return pos;
    },    
    set_Visible : function(val) {
      this.el.style.visibility=val?'visible':'hidden';
    },
    get_Visible : function(val) {
      return this.el.style.visibility=='visible';
    },
    SetupDragDrop : function(target) {
      var dist = new Object();
      //var ss = thisPage.SelectStart;
      //var win = new Dom.Page();
      //win.init();
      
      var cancelSel = function(sender, e) {
        event.returnValue = false;
      }
      var mouseMove = function(sender, e) { 
        var pos = new Position(); // TODO: namespace
        pos.left = e.get_Position().left - dist.width;
        pos.top = e.get_Position().top - dist.height;
        target.set_Position(pos);
      }
      var mouseUp = function(sender, e) { 
        thisPage.get_MouseMove().remove(mouseMove);
        thisPage.get_MouseUp().remove(mouseUp);
        //ss.remove(cancelSel);
      }
      this.get_MouseDown().add(function(sender, e) { 
        var tp = target.get_Position();
        var cp = e.get_Position();
        dist.width = cp.left - tp.left;
        dist.height = cp.top - tp.top;
        thisPage.get_MouseMove().add(mouseMove);
        thisPage.get_MouseUp().add(mouseUp);
        //ss.add(cancelSel);
      });
    },
    GetChild : function(id) {
      function getElChild(el, id) {
        if (!el||!el.tagName||!el.childNodes) return null;
        //alert("found:"+el.id+" looking for:"+id);
        if (el.id == id) return el;
        
        for(var i=0; i<el.childNodes.length; i++) {
          var sub = el.childNodes[i];
          var subRet = getElChild(sub, id);
          if (subRet) return subRet;
        }
      }
      var e = getElChild(this.el, this.id+"_"+id);
      if (e)
        return CreateObject(new DiscriminatedUnion(), ["Some", [WrapElement(e)]]);
      else
        return CreateObject(new DiscriminatedUnion(), ["None", []]);
    },
    AppendChild : function(obj) {
      this.el.appendChild(obj.el);
    },
    AddCssClass : function(cls) {
      this.el.className = this.el.className + " " + cls;
    },
    RemoveCssClass : function(cls) {
      var sp = this.el.className.split(" ");
      var res = "";
      cls = cls.replaceAll(" ", "");
      for(var i=0; i<sp.length; i++)
      {
        var cn = sp[i].replaceAll(" ", "");
        if (cn != cls) res = res + " " + cn;
      }
      this.el.className = res;
    },
    
    get_ClientMouseDown : function()    { return this.mouseDown; },
    get_ClientMouseUp : function()      { return this.mouseUp; },
    get_ClientMouseMove : function()    { return this.mouseMove; },
    get_ClientSelectStart : function()  { return this.selectStart; },
    get_ClientClick : function()        { return this.click; },
    
    get_InnerHtml : function()    { return this.el.innerHTML; },
    set_InnerHtml : function(val) { this.el.innerHTML = val; },
    get_InnerText : function()    { return this.el.innerText; },
    set_InnerText : function(val) { this.el.innerText = val; }
}
Dom.Element.registerClass('Dom.Element');

// ************************************************************************************************

Dom.Label = function() { 
    Dom.Label.initializeBase(this);
}
Dom.Label.prototype = {
    ctor : function(el) {
        Dom.Label.callBaseMethod(this, "ctor", [el]);
    },
    get_Text : function() {
      return this.el.innerHTML;
    },
    set_Text : function(val) {
      this.el.innerHTML = val;
    }
};
Dom.Label.registerClass('Dom.Label', Dom.Element);

Dom.Button = function() {
    Dom.Button.initializeBase(this);
}
Dom.Button.prototype = {
    ctor : function(el) {
        Dom.Button.callBaseMethod(this, "ctor", [el]);
    },
    get_Text : function() {
      return this.el.innerHTML;
    },
    set_Text : function(val) {
      this.el.innerHTML = val;
    }
};
Dom.Button.registerClass('Dom.Button', Dom.Element);

Dom.TextBox = function() {
    Dom.TextBox.initializeBase(this);
    this.textchanged = null;
    this.keyup = null;
    this.keydown = null;
    this.keypress = null;
}
Dom.TextBox.prototype = {
    ctor : function(el) {
        Dom.TextBox.callBaseMethod(this, "ctor", [el]);
        this.textchanged = createEvent();
        this.keyup = createEvent();
        this.keydown = createEvent();
        this.keypress = createEvent();        
        attachHandler(this.el, 'change', Function.createDelegate(this, createGenericHandler(this.textchanged) ));
        attachHandler(this.el, 'keyup', Function.createDelegate(this, createGenericHandler(this.keyup) ));
        attachHandler(this.el, 'keydown', Function.createDelegate(this, createGenericHandler(this.keydown) ));
        attachHandler(this.el, 'keypress', Function.createDelegate(this, createGenericHandler(this.keypress) ));
    },
    get_Text : function() {
      return this.el.value;
    },
    set_Text : function(val) {
      this.el.value = val;
    },
    get_ClientTextChanged : function() { return this.textchanged; },
    get_ClientKeyUp : function() { return this.keyup; },
    get_ClientKeyDown : function() { return this.keydown; },
    get_ClientKeyPress : function() { return this.keypress; }
};
Dom.TextBox.registerClass('Dom.TextBox', Dom.Element);

Dom.DropDownList = function() {
    Dom.DropDownList.initializeBase(this);
    this.selectionchanged = null;
}
Dom.DropDownList.prototype = {
    ctor : function(el) {
        Dom.DropDownList.callBaseMethod(this, "ctor", [el]);
        this.selectionchanged = createEvent();
        attachHandler(this.el, 'change', Function.createDelegate(this, createGenericHandler(this.selectionchanged) ));
    },
    get_SelectedKey : function() {
      return this.el.value;
    },
    set_SelectedKey : function(val) {
      alert('not supported!'); this.el.value = val;
    },
    get_SelectedValue : function() {
      alert('not supported!'); return alert(this.el.value);
    },
    set_SelectedValue : function(val) {
      alert('not supported!'); this.el.value = val;
    },
    get_ClientSelectionChanged : function() { return this.selectionchanged; }
};
Dom.DropDownList.registerClass('Dom.DropDownList', Dom.Element);

Dom.RadioButton = function() {
    Dom.RadioButton.initializeBase(this);
}
Dom.RadioButton.prototype = {
    ctor : function(el) {
        Dom.RadioButton.callBaseMethod(this, "ctor", [el]);
    },
    get_Checked : function() {
      return this.el.checked;
    },
    set_Checked : function(val) {
      this.el.checked = val;
    },
    get_ClientCheckedChanged : function() { return this.get_ClientClick(); }
};
Dom.RadioButton.registerClass('Dom.RadioButton', Dom.Element);



Dom.HyperLink = function() {
    Dom.HyperLink.initializeBase(this);
}
Dom.HyperLink.prototype = {
    ctor : function(el) {
        Dom.HyperLink.callBaseMethod(this, "ctor", [el]);
    },
    get_Text : function() {
      return this.el.innerHTML;
    },
    set_Text : function(val) {
      this.el.innerHTML = val;
    },
    get_NavigateUrl : function() {
      return this.el.href;
    },
    set_NavigateUrl : function(val) {
      this.el.href = val;
    }
};
Dom.HyperLink.registerClass('Dom.HyperLink', Dom.Element);

Dom.Image = function() {
    Dom.Image.initializeBase(this);
}
Dom.Image.prototype = {
    ctor : function(el) {
        Dom.Image.callBaseMethod(this, "ctor", [el]);
    },
    get_ImageUrl : function() {
      return this.el.src;
    },
    set_ImageUrl : function(val) {
      this.el.src = val;
    }
};
Dom.Image.registerClass('Dom.Image', Dom.Element);

Dom.LinkButton = function() {
    Dom.LinkButton.initializeBase(this);
    this.nclick = null;
}
Dom.LinkButton.prototype = {
    ctor : function(el) {
        this.nclick = createEvent();
        Dom.LinkButton.callBaseMethod(this, "ctor", [el]);
        var ce = Dom.LinkButton.callBaseMethod(this, "get_ClientClick", []);
        ce.add(Function.createDelegate(this, function (s, e) {
            if (this.get_Enabled()) 
              this.nclick.invoke(s, e);
            else
              e.set_Canceled(true);
          }));
    },
    get_Text : function() {
      return this.el.innerHTML;
    },
    set_Text : function(val) {
      this.el.innerHTML = val;
    },
    get_Enabled : function() {
      return !this.el.disabled;
    },
    set_Enabled : function(val) {
      this.el.disabled = !val;
    },
    get_ClientClick : function() { return this.nclick; }
};
Dom.LinkButton.registerClass('Dom.LinkButton', Dom.Element);